<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { updateUploadAvatar, getAdminProfile} from '@/api/admin'
import { ElMessage } from 'element-plus'

const userInfo = ref({
  avatar: ''
})
const imgUrl = ref('')
const loading = ref(false)
// 使用onMounted来异步获取数据
onMounted(async () => {
  try {
    const response = await getAdminProfile()
    const data = response.data || response
    userInfo.value = data
    imgUrl.value = data.avatar_url || ''
  } catch (error) {
    console.error('获取管理员信息失败:', error)
  }
})
const uploadRef = ref()
const selectedFile = ref(null)

// 文件选择处理
const onFileSelect = (uploadFile) => {
  // 创建本地预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    imgUrl.value = e.target.result
  }
  reader.readAsDataURL(uploadFile.raw)
  selectedFile.value = uploadFile.raw
}

// 实际上传处理
const onUploadAvatar = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  const formData = new FormData()
  formData.append('avatar', selectedFile.value)

  try {
    loading.value = true
    const response = await updateUploadAvatar(formData)
    ElMessage.success('头像上传成功！')
    loading.value = false
    // 更新头像URL
    if (response.avatar_url) {
      imgUrl.value = response.avatar_url
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败：' + (error.response?.data?.message || error.message || '未知错误'))
  }
}
</script>

<template>
  <div class="admin-avatar">
    <el-card class="avatar-card">
      <template #header>
        <h2>更换头像</h2>
      </template>

      <el-row justify="center">
        <el-col :span="24">
          <div class="avatar-container">
            <el-upload
              ref="uploadRef"
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="onFileSelect"
              accept="image/*"
            >
              <img v-if="imgUrl" :src="imgUrl" class="avatar" />
              <img v-else src="@/assets/avatar.jpg" class="avatar" />
            </el-upload>

            <div class="avatar-actions">
              <el-button type="primary" :icon="Plus" @click="uploadRef?.$el?.querySelector('input')?.click()">
                选择图片
              </el-button>
              <el-button type="success" :icon="Upload" @click="onUploadAvatar" :disabled="!selectedFile">
                上传头像
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.admin-avatar {
  padding: 20px;
}

.avatar-card {
  max-width: 800px;
  margin: 0 auto;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 24px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 2px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 200px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}
</style>
